package srx.open.com.activity;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;

import com.baidu.mapapi.SDKInitializer;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import cn.bmob.im.BmobChat;
import cn.bmob.im.BmobChatManager;
import cn.bmob.im.BmobUserManager;
import cn.bmob.im.bean.BmobInvitation;
import cn.bmob.im.bean.BmobMsg;
import cn.bmob.im.config.BmobConfig;
import cn.bmob.im.inteface.EventListener;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import srx.open.com.R;
import srx.open.com.adapter.TabPageAdapter;
import srx.open.com.bean.User;
import srx.open.com.fragment.MineFragment;
import srx.open.com.fragment.MyMsgFragment;
import srx.open.com.fragment.NearbyFragment;
import srx.open.com.fragment.TutorFragment;
import srx.open.com.receviers.MyMessageReceiver;
import srx.open.com.utils.CommonUtils;
import srx.open.com.utils.Config;
import srx.open.com.utils.Constants;
import srx.open.com.utils.FilePathGenerator;
import srx.open.com.utils.ImageLoadOptions;
import srx.open.com.utils.Log;
import srx.open.com.utils.OpenToast;
import srx.open.com.utils.PhotoUtil;
import srx.open.com.utils.UserUtils;
import srx.open.com.widgets.OpenViewPager;

/**
 * 基础activity,主要初始化一些控件和函数.
 *
 * @author hailongqiu 356752238@qq.com
 */

public class BaseActivity extends FragmentActivity implements OnClickListener, EventListener {

    public static final String TAG = "BaseActivity";
    public static final int SWITCH_TUTOR_PAGE = 0;
    public static final int SWITCH_NEARBY_PAGE = 1;
    public static final int SWITCH_MSG_PAGE = 2;
    public static final int SWITCH_MINE_PAGE = 3;

    /* 一些重要的变量 */
    public Context mContext;
    public BaiduReceiver mBaiduReceiver;
    public BmobUserManager mUserManager;
    public LayoutInflater mInflater;
    /* fragment控制 */
    OpenViewPager home_viewpager;
    public ArrayList<Fragment> mFragmentList;
    public TabPageAdapter mFragmentPageAdapter;

    public View home_lay;
    public View start_page_rlay;

    @Override
    protected void onStart() {
        super.onStart();
        initLog(); /* 初始化log */
        initImageLoader(); /* 初始化 u-image-loader */
        initLocalDatas(); /* 初始化本地的一些数据 */
        initRegisterReceivers();
    }

    NewBroadcastReceiver  newReceiver;

    private void initNewMessageBroadCast() {
        // 注册接收消息广播
        newReceiver = new NewBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(BmobConfig.BROADCAST_NEW_MESSAGE);
        //优先级要低于ChatActivity
        intentFilter.setPriority(3);
        registerReceiver(newReceiver, intentFilter);
    }

    /**
     * 新消息广播接收者
     *
     */
    private class NewBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //刷新界面
            refreshNewMsg(null);
            // 记得把广播给终结掉
            abortBroadcast();
        }
    }

    /** 刷新界面
     * @Title: refreshNewMsg
     * @Description: TODO
     * @param @param message
     * @return void
     * @throws
     */
    private void refreshNewMsg(BmobMsg message){
        // 声音提示
//        boolean isAllow = CustomApplcation.getInstance().getSpUtil().isAllowVoice();
//        if(isAllow){
//            CustomApplcation.getInstance().getMediaPlayer().start();
//        }
        //也要存储起来
        if(message!=null){
            BmobChatManager.getInstance(BaseActivity.this).saveReceiveMessage(true,message);
        }
        //当前页面如果为会话页面，刷新此页面
        if (mMyMsgFragment != null) {
            mMyMsgFragment.refresh();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MyMessageReceiver.ehList.add(this);// 监听推送的消息
        //清空
        MyMessageReceiver.mNewNum=0;
    }

    @Override
    protected void onPause() {
        super.onPause();
        MyMessageReceiver.ehList.remove(this);// 取消监听推送的消息
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//		DataBaseHelper dataBaseHelper = ((SrxApplication)getApplication()).getDataBaseHelper();
//		if (dataBaseHelper != null)
//			dataBaseHelper.closeDatabase();
        //取消定时检测服务
        BmobChat.getInstance(this).stopPollService();
        //
        try {
            unregisterReceiver(newReceiver);
        } catch (Exception e) {
        }
    }

    void initAllDatas() {
        Bmob.initialize(this, Config.APPLICATION_ID); /* Bmob 初始化 */
        mUserManager = BmobUserManager.getInstance(this);
        mFragmentList = new ArrayList<Fragment>();
        //
        //开启定时检测服务（单位为秒）-在这里检测后台是否还有未读的消息，有的话就取出来
        //如果你觉得检测服务比较耗流量和电量，你也可以去掉这句话-同时还有onDestory方法里面的stopPollService方法
        BmobChat.getInstance(this).startPollService(1);
        //开启广播接收器
        initNewMessageBroadCast();
    }

    private void initLog() {
        Log.setEnabled(Config.IS_LOG);
        Log.setLog2ConsoleEnabled(Config.IS_DEBUG);
        Log.setGlobalTag(TAG);
        if (CommonUtils.checkSdCard()) {
            try {
                Log.setLog2FileEnabled(true);
                Log.setFilePathGenerator(new FilePathGenerator.DefaultFilePathGenerator(
                        Constants.MY_ROOT_CACHE_DIR, "app", ".log"));
            } catch (Exception e) {
                e.printStackTrace();
                Log.setLog2FileEnabled(false);
            }
        }
        Log.clearLogFilters();
    }

    /**
     * 初始化imageLoader
     */
    public void initImageLoader() {
        ImageLoadOptions.initImageLoader(mContext);
        // File cacheDir =
        // StorageUtils.getCacheDirectory(getApplicationContext());
//        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
//                getApplicationContext())
//                .memoryCache(new LruMemoryCache(5 * 1024 * 1024))
//                .memoryCacheSize(10 * 1024 * 1024)
//                        // .discCache(new UnlimitedDiscCache(cacheDir))
//                .discCacheFileNameGenerator(new HashCodeFileNameGenerator())
//                .build();
//        ImageLoader.getInstance().init(config);
    }

    public void initLocalDatas() {
        try {
            String savePath = Constants.MY_IMAGE_CACHE_RDIR;
            File file = new File(savePath);
            if (!file.exists()) {
                Log.i("创建本地图片缓存目录成功");
                file.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  注册广播.
     */
    void initRegisterReceivers() {
        // 注册地图 SDK 广播监听者
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
        mBaiduReceiver = new BaiduReceiver();
        registerReceiver(mBaiduReceiver, iFilter);
    }

    @Override
    public void onMessage(BmobMsg bmobMsg) {
        refreshNewMsg(bmobMsg);
    }

    @Override
    public void onReaded(String s, String s1) {

    }

    @Override
    public void onNetChange(boolean isNetConnected) {
        if (isNetConnected) {
            OpenToast.showMsg("网络未连接");
        }
    }

    @Override
    public void onAddUser(BmobInvitation bmobInvitation) {
        // 暂时未开启这个功能. (好友)
    }

    @Override
    public void onOffline() {
        OpenToast.showMsg("你的账号已在其它设备登陆!!");
    }

    /**
     * 构造广播监听类，监听 SDK key 验证以及网络异常广播
     */
    public class BaiduReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String s = intent.getAction();
            if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
                OpenToast.showMsg("key 验证出错! 请在 AndroidManifest.xml 文件中检查 key 设置");
            } else if (s
                    .equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
                OpenToast.showMsg("当前网络连接不稳定，请检查您的网络设置!");
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    void initAllWidgets() {
        /* 初始化一些重要的变量 */
        initUiValues();
        /* 初始化 Toast */
        OpenToast.initToast(mContext);
        /* 初始化工具条的控件以及事件 */
        initTabToolWidgets();
        /* 初始化viewpager - framgnet */
        initViewPager();
        //
        home_lay = findViewById(R.id.home_lay);
        home_lay.setAlpha(0.0f);
        start_page_rlay = findViewById(R.id.start_page_rlay);
        // 执行动画.
        AlphaAnimation aAnima = new AlphaAnimation(0.95f, 1.0f);//从全不透明变为全透
        aAnima.setDuration(1888);
        aAnima.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                start_page_rlay.setVisibility(View.GONE);
                home_lay.setAlpha(1.0f);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        start_page_rlay.startAnimation(aAnima);
    }

    /**
     * 初始化一些重要的变量
     */
    private void initUiValues() {
        mContext = getApplicationContext();
        mInflater = getLayoutInflater();
    }

    /*
     * 初始化工具条的控件以及事件
     */
    private void initTabToolWidgets() {
        View tab_tutor_rb = findViewById(R.id.tab_tutor_rb); // 首页.
        View tab_nearby_rb = findViewById(R.id.tab_nearby_rb); // 附近
        View tab_pub_rb = findViewById(R.id.tab_pub_btn); // 发布
        View tab_msg_rb = findViewById(R.id.tab_msg_rb); // 消息
        View tab_mine_rb = findViewById(R.id.tab_mine_rb); // 我的
        // ...
        tab_tutor_rb.setOnClickListener(this);
        tab_nearby_rb.setOnClickListener(this);
        tab_pub_rb.setOnClickListener(this);
        tab_msg_rb.setOnClickListener(this);
        tab_mine_rb.setOnClickListener(this);
    }

    MyMsgFragment mMyMsgFragment;

    /*
     * 初始化viewpager.
     */
    private void initViewPager() {
        home_viewpager = (OpenViewPager) findViewById(R.id.home_viewpager);
        //
        TutorFragment tutorFragment = (TutorFragment) TutorFragment
                .newInstance("首页页面模块");
        NearbyFragment nearbyFragment = (NearbyFragment) NearbyFragment
                .newInstance("附近页面模块");
        mMyMsgFragment = (MyMsgFragment) MyMsgFragment
                .newInstance("消息页面模块");
        MineFragment mineFragment = (MineFragment) MineFragment
                .newInstance("我的页面模块");
        // Fragment数据添加.
        mFragmentList.add(tutorFragment);
        mFragmentList.add(nearbyFragment);
        mFragmentList.add(mMyMsgFragment);
        mFragmentList.add(mineFragment);
        //
        mFragmentPageAdapter = new TabPageAdapter(getSupportFragmentManager(),
                mContext, mFragmentList);
        home_viewpager.setAdapter(mFragmentPageAdapter);
        home_viewpager.setCurrentItem(0, false); // 默认页面.
        home_viewpager.setOffscreenPageLimit(4); // 缓存页数.
    }

    /*
     * viewpager-页面切换.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab_tutor_rb: // 首页
                home_viewpager.setCurrentItem(SWITCH_TUTOR_PAGE, false);
                break;
            case R.id.tab_nearby_rb: // 附近
                home_viewpager.setCurrentItem(SWITCH_NEARBY_PAGE, false);
                break;
            case R.id.tab_pub_btn: // 发布
                User user = UserUtils.getCurrentUser(mContext);
                if (user != null) {
                    openActivity(PublishCourseActivity.class);
                } else {
                    OpenToast.showMsg("需要登录才能使用此功能");
                }
                break;
            case R.id.tab_msg_rb: // 消息
                home_viewpager.setCurrentItem(SWITCH_MSG_PAGE, false);
                break;
            case R.id.tab_mine_rb: // 我的
                home_viewpager.setCurrentItem(SWITCH_MINE_PAGE, false);
                break;
            default:
                break;
        }
    }

    private long mExitTime; // 时间戳.

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            OpenToast.showMsg("再按一次退出");
            Log.d("----onBackPressed 再按一次退出----mExitTime:" + mExitTime);
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            Log.d("----onBackPressed finish----");
        }
    }

    private String filePath = "";
    private boolean isFromCamera = false; // 区分拍照旋转
    private int degree = 0;
    private String path;
    public ImageView iv_set_avator;

    /**
     * 本地相册
     */
    public void callLocalActionPick() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent,
                Constants.REQUESTCODE_UPLOADAVATAR_LOCATION);
    }

    /**
     * 照相.
     */
    public void callImageCapture() {
        try {
            File dir = new File(Constants.MY_IMAGE_CACHE_RDIR);
            // 检查目录是否存在.
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 原图
            File file = new File(dir, new SimpleDateFormat("yyMMddHHmmss")
                    .format(new Date()));
            filePath = file.getAbsolutePath();// 获取相片的保存路径
            Uri imageUri = Uri.fromFile(file);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent,
                    Constants.REQUESTCODE_UPLOADAVATAR_CAMERA);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(e.getMessage());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            /* 本地相册返回 */
            case Constants.REQUESTCODE_UPLOADAVATAR_LOCATION:
                Log.i("本地相册返回:" + Constants.REQUESTCODE_UPLOADAVATAR_LOCATION);
                Uri uri = null;
                if (data == null) {
                    return;
                }
                if (resultCode == RESULT_OK) {
                    if (!Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        OpenToast.showMsg("SD不可用");
                        return;
                    }
                    isFromCamera = false;
                    uri = data.getData();
                    startImageAction(uri, 200, 200,
                            Constants.REQUESTCODE_UPLOADAVATAR_CROP, true);
                } else {
                    OpenToast.showMsg("照片获取失败");
                }
                break;
			/* 照相返回 */
            case Constants.REQUESTCODE_UPLOADAVATAR_CAMERA:
                Log.i("照相返回:" + Constants.REQUESTCODE_UPLOADAVATAR_CAMERA);
                if (resultCode == RESULT_OK) {
                    if (!Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        OpenToast.showMsg("SD不可用");
                        return;
                    }
                    isFromCamera = true;
                    File file = new File(filePath);
                    degree = PhotoUtil.readPictureDegree(file.getAbsolutePath());
                    Log.i("life", "拍照后的角度：" + degree);
                    startImageAction(Uri.fromFile(file), 200, 200,
                            Constants.REQUESTCODE_UPLOADAVATAR_CROP, true);
                }
                break;
			/* 图片裁剪返回 */
            case Constants.REQUESTCODE_UPLOADAVATAR_CROP:
                if (data == null) {
                    return;
                } else {
                    saveCropAvator(data);
                }
                // 初始化文件路径
                filePath = "";
                // 上传头像
                uploadAvatar();
                break;
        }
    }

    /**
     * 裁剪图片.
     */
    private void startImageAction(Uri uri, int outputX, int outputY,
                                  int requestCode, boolean isCrop) {
        try {
            Intent intent = null;
            if (isCrop) {
                intent = new Intent("com.android.camera.action.CROP");
            } else {
                intent = new Intent(Intent.ACTION_GET_CONTENT, null);
            }
            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", outputX);
            intent.putExtra("outputY", outputY);
            intent.putExtra("scale", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            intent.putExtra("return-data", true);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("noFaceDetection", true); // no face detection
            startActivityForResult(intent, requestCode);
            Log.i("裁剪图片...");
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(e.getMessage());
        }
    }

    /**
     * 保存裁剪的头像
     *
     * @param data
     */
    private void saveCropAvator(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap bitmap = extras.getParcelable("data");
            Log.i("life", "avatar - bitmap = " + bitmap);
            if (bitmap != null) {
                bitmap = PhotoUtil.toRoundCorner(bitmap, 10);
                if (isFromCamera && degree != 0) {
                    bitmap = PhotoUtil.rotaingImageView(degree, bitmap);
                }
                Log.i("保存裁剪的图片...");
                // 设置头像.
//                if (iv_set_avator != null)
//                    iv_set_avator.setImageBitmap(bitmap);
                // 保存图片
                String filename = new SimpleDateFormat("yyMMddHHmmss")
                        .format(new Date()) + ".png";
                path = Constants.MY_IMAGE_CACHE_RDIR + "/" + filename;
                PhotoUtil.saveBitmap(Constants.MY_IMAGE_CACHE_RDIR, filename,
                        bitmap, true);
                // 上传头像
                if (bitmap != null && bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            }
        }
    }

    /**
     * 上传头像.
     */
    private void uploadAvatar() {
        final BmobFile bmobFile = new BmobFile(new File(path));
        bmobFile.upload(this, new UploadFileListener() {

            @Override
            public void onSuccess() {
                String url = bmobFile.getFileUrl(mContext);
                // 更新BmobUser对象
                updateUserAvatar(url);
            }

            @Override
            public void onProgress(Integer arg0) {
            }

            @Override
            public void onFailure(int arg0, String msg) {
                OpenToast.showMsg("头像上传失败：" + msg);
            }
        });
    }

    /**
     * 更新用户数据.
     */
    private void updateUserAvatar(final String url) {
        User u = new User();
        u.setAvatar(url);
        u.setNick("我的" + url); // test
        //
        User current = UserUtils.getCurrentUser(mContext);
        u.setObjectId(current.getObjectId());
        u.update(this, new UpdateListener() {
            @Override
            public void onSuccess() {
                OpenToast.showMsg("头像更新成功！");
                // 更新头像
                refreshAvatar(url);
            }

            @Override
            public void onFailure(int code, String msg) {
                OpenToast.showMsg("头像更新失败：" + msg);
            }
        });
    }

    private void refreshAvatar(String avatar) {
        if (!StringUtils.isEmpty(avatar)) {
            ImageLoader.getInstance().displayImage(avatar, iv_set_avator,
                    ImageLoadOptions.getOptions());
        } else {
            iv_set_avator.setImageResource(R.drawable.ic_launcher);
        }
    }

    public void openActivity(Class<?> cls) {
        Intent intents = new Intent(mContext, cls);
        startActivity(intents);
    }

}
